import flet as ft
from services.device_service import DeviceService
from datetime import datetime


class QueryPage:
	def __init__(self, page):
		self.page = page
		self.service = DeviceService()
		self.current_page = 1
		self.page_size = 10
		self.build()
	
	def build(self):
		# 查询条件控件
		self.search_input = ft.TextField(label="设备名称/SN号", expand=True)
		self.device_type_filter = ft.Dropdown(
			label="设备类型",
			options=[ft.dropdown.Option("全部")] + self._get_device_types(),
			value="全部"
		)
		self.status_filter = ft.Dropdown(
			label="归还状态",
			options=[
				ft.dropdown.Option("全部"),
				ft.dropdown.Option("未归还"),
				ft.dropdown.Option("已归还")
			],
			value="全部"
		)
		self.start_date = ft.TextField(label="开始日期", hint_text="YYYY-MM-DD")
		self.end_date = ft.TextField(label="结束日期", hint_text="YYYY-MM-DD")
		
		# 结果表格
		self.result_table = ft.DataTable(
			columns=[
				ft.DataColumn(ft.Text("设备名称")),
				ft.DataColumn(ft.Text("类型")),
				ft.DataColumn(ft.Text("对方信息")),
				ft.DataColumn(ft.Text("借出日期")),
				ft.DataColumn(ft.Text("状态"), numeric=True)
			],
			rows=[]
		)
		
		# 分页控件
		self.page_info = ft.Text()
		self.prev_btn = ft.IconButton(
			icon=ft.icons.ARROW_BACK,
			on_click=lambda e: self._change_page(-1)
		)
		self.next_btn = ft.IconButton(
			icon=ft.icons.ARROW_FORWARD,
			on_click=lambda e: self._change_page(1)
		)
		
		self.view = ft.Column(
			controls=[
				ft.Text("设备查询", size=24),
				ft.Row([
					self.search_input,
					self.device_type_filter,
					self.status_filter
				]),
				ft.Row([self.start_date, self.end_date]),
				ft.ElevatedButton("搜索", on_click=self.search),
				ft.Divider(),
				ft.Row([
					ft.Text("查询结果:"),
					ft.Row([self.prev_btn, self.page_info, self.next_btn])
				]),
				ft.Expanded(child=ft.ListView([self.result_table], expand=True))
			],
			spacing=15,
			expand=True
		)
	
	def _get_device_types(self):
		return [ft.dropdown.Option("手机"), ft.dropdown.Option("平板"),
		        ft.dropdown.Option("手表"), ft.dropdown.Option("扫描笔")]
	
	def search(self, e):
		try:
			filters = {
				"device_name": self.search_input.value,
				"device_type": self.device_type_filter.value if self.device_type_filter.value != "全部" else None,
				"status": 1 if self.status_filter.value == "已归还" else 0 if self.status_filter.value == "未归还" else None,
				"start_date": self.start_date.value,
				"end_date": self.end_date.value
			}
			
			result = self.service.search_records(filters, self.current_page, self.page_size)
			self._update_table(result["data"])
			self._update_pagination(result["total"])
		except Exception as ex:
			self.page.show_snack_bar(
				ft.SnackBar(ft.Text(f"查询错误: {str(ex)}", color=ft.colors.RED_200))
			)
	
	def _update_table(self, data):
		self.result_table.rows.clear()
		for item in data:
			self.result_table.rows.append(
				ft.DataRow(
					cells=[
						ft.DataCell(ft.Text(item["device_name"])),
						ft.DataCell(ft.Text(item["device_type"])),
						ft.DataCell(ft.Text(item["counterpart"])),
						ft.DataCell(ft.Text(item["borrow_date"])),
						ft.DataCell(ft.Text("已归还" if item["status"] else "未归还"))
					]
				)
			)
		self.page.update()
	
	def _update_pagination(self, total):
		total_pages = (total + self.page_size - 1) // self.page_size
		self.page_info.value = f"第 {self.current_page}/{total_pages} 页 共 {total} 条"
		self.prev_btn.disabled = self.current_page <= 1
		self.next_btn.disabled = self.current_page >= total_pages
		self.page.update()
	
	def _change_page(self, delta):
		self.current_page += delta
		self.search(None)
